<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <el-card>
        <div class="opeation">
            <el-input
                v-model="keyword"
                style="max-width: 300px"
                placeholder="请输入品牌名称"
                class="input-with-select"
                >
                <template #append>
                    <el-button icon="Search" @click="queryBrand" v-has="'btn.Trademark.search'"/>
                </template>
                </el-input>
            <el-button style="margin-left: 20px;" type="primary" icon="Plus" @click="addBrand" v-has="'btn.Trademark.add'">添加品牌</el-button>
        </div>
        <el-table :data="tableData" stripe="true" style="margin: 10px 0 20px;" border>
            <el-table-column prop="id" label="序号" align="center" width="100"></el-table-column>
            <el-table-column prop="tmName" label="品牌名称" align="center"></el-table-column>
            <el-table-column prop="LogoUrl" label="品牌LOGO" align="center">
                <template #default="scope">
                    <img :src="scope.row.logoUrl" style="width: 100px; height: 60px;">
                </template>
            </el-table-column>
            <el-table-column prop="" label="操作" align="center" width="300">
                <template #default="scope">
                    <el-button type="warning" size="mini" icon="Edit" @click="editBrand(scope.row.id)" v-has="'btn.Trademark.update'">编辑</el-button>
                    <el-popconfirm :title="`是否确认删除商品【${scope.row?.tmName||''}】?`" width="250px" icon="Delete" @confirm="confirmDelete(scope.row.id)">
                        <template #reference>
                            <el-button type="danger" size="mini" icon="Delete" v-has="'btn.Trademark.remove'">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 30, 50, 100]"
                :total
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </el-card>
    <el-dialog
        v-model="dialogVisible"
        :title="brandDto.id ? '编辑品牌' : '添加品牌'"
        width="600"
        @closed="closeDialog"
    >
        <el-form
            ref="brandDtoRef"
            :model="brandDto"
            :rules="brandRules"
            label-width="auto"
            class="demo-ruleForm"
        >
            <el-form-item label="商品名称" prop="tmName">
                <el-input v-model="brandDto.tmName" />
            </el-form-item>
            <el-form-item label="商品LOGO" prop="logoUrl">
                <UploadFileSingle @imgUrlChange="imgUrlChange" ref="uploadFileSingle"></UploadFileSingle>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAdd">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
    import { ref, reactive, onMounted, nextTick } from "vue";
    import { ElMessage, MessageParamsWithType } from "element-plus";
    import productApi from "@/api/product";


    let keyword = ref('');
    let currentPage = ref(1);
    let pageSize = ref(5);
    let total = ref(0);
    let tableData = ref([]);
    let brandDto = reactive({
        id:"",
        tmName: "",
        logoUrl: ""
    });
    let dialogVisible = ref(false);
    const brandDtoRef = ref();
    const uploadFileSingle = ref();

    const validatorName = (rule, value: string, callback) => {
        if (!value) {
            callback(new Error("请输入品牌名称"));
        } else if (value.length < 2 || value.length > 10) {
            callback(new Error("品牌名称长度在 2 到 10 个字符"));
        }else {
            callback();
        }
    }
    const brandRules = reactive({
        tmName: [
            { required: true, trigger: 'blur', validator:validatorName },
            // { min: 2, max: 10, message: "品牌名称长度在 2 到 10 个字符", trigger: 'blur' }
        ],
        logoUrl:[
            { required: true, message: "请上传品牌LOGO", trigger: 'change' }
        ]
    });

    function handleSizeChange(e: number){
        pageSize.value = e;
        getBrandList();
    }
    function handleCurrentChange(e: number){
        currentPage.value = e;
        getBrandList();
    }

    async function getBrandList() {
        const res = await productApi.getBrandList(currentPage.value, pageSize.value);
        if(res.code === 200){
            tableData.value = res.data.records;
            total.value = res.data.total;
        }else ElMessage.error(res.message);
    }

    async function queryBrand() {
        if(keyword.value){
            const res = await productApi.getBrandListByKeyword(keyword.value);
            if (res.code === 200) {
                tableData.value = res.data;
                total.value = res.data?.length;
                currentPage.value = 1;
            } else ElMessage.error(res.message);
        }else{
            getBrandList();
        }
    }

    const addBrand = () => {
        dialogVisible.value = true;
    }
    const editBrand = async (id) => {
        const res = await productApi.getBrandById(id);
        if(res.code === 200){
            Object.assign(brandDto, res.data)
            dialogVisible.value = true;
            nextTick(()=>{
                uploadFileSingle.value.imageUrl = brandDto.logoUrl;
            })
        }else ElMessage.error(res.message);
    }
    const closeDialog = () => {
        resetForm();
        nextTick(()=>{
            Object.keys(brandRules).forEach((key) => {
                brandDtoRef.value.clearValidate(key);
            })
        })
    }

    const resetForm = () => {
        dialogVisible.value = false;
        brandDto = reactive({
            id:"",
            tmName: "",
            logoUrl: ""
        });
        uploadFileSingle.value.imageUrl = "";
        brandDtoRef.value.resetFields();
    }

    const confirmDelete = (id: number) => {
        productApi.deleteBrandById(id).then((res: { code: number; message: MessageParamsWithType; }) => {
            if (res.code === 200) {
                ElMessage.success("删除成功!");
                getBrandList();
            } else ElMessage.error(res.message);
        });
    }

    const confirmAdd = () => {
        brandDtoRef.value.validate(async (valid: boolean) => {
            if (valid) {
                const res = await productApi[brandDto.id?'editBrand':'insertBrand'](brandDto);
                if(res.code === 200){
                    ElMessage.success(`${brandDto?.id ? "修改" : "添加"}成功!`);
                    resetForm();
                    getBrandList();
                }else ElMessage.error(res.message);
            }
        })
     }

    const imgUrlChange = (imgUrl: string) => {
        brandDto.logoUrl = imgUrl;
        //图片上传成功清楚校验提示信息
        if(imgUrl) brandDtoRef.value.clearValidate('logoUrl');
    }

    onMounted(() => {
        getBrandList();
    });
</script>

<style scoped lang="scss">
    .opeation{
        display: flex;
        align-items: center;
    }

    .pagination{
        display: flex;
        justify-content: flex-end;
    }
</style>